Grails : Hibernate Integration
This page last changed on Feb 28, 2006 by glaforge.
Hibernate integrationMapping Domain Classes with HibernateIf GORM (Grails Object Relational Mapping) is not flexible enough for your liking you can alternatively map your domain class using Hibernate. To do this create a "hibernate.cfg.xml" file in the "%PROJECT_HOME%\hibernate" directory of your project and the corresponding Hbm mapping xml file for your domain class. For more info on how to do this read the documentation on mapping on the Hibernate Website This will allow you to map Grails domain classes onto a wider range of legacy systems and be more flexible in the creation of your database schema. Using Existing Hibernate Data ModelsGrails also allows you to write your domain model in Java or re-use an existing domain model that has been mapped using Hibernate. all you have to do is place the necessary "hibernate.cfg.xml" file and corresponding mappings files in the "%PROJECT_HOME%\hibernate" directory. You will still be able to call all of the dynamic persistent and query methods allowed in GORM! Mapping with Hibernate AnnotationsGrails also supports creating domain classes mapped with Hibernate's Java 5.0 Annotations support. To do so you need to tell Grails that you are using an annotation configuration by setting the "configClass" in your data source project as follows: import org.codehaus.groovy.grails.orm.hibernate.cfg.GrailsAnnotationConfiguration class ApplicationDataSource { @Property configClass = GrailsAnnotationConfiguration.class ... // remaining properties } That's it for the configuration! Oh and make sure you have Java 5.0 installed as this is required to use annotations. Now to create an annotated class we simply create a new Java class and use the annotations defined as part of the EJB 3.0 spec (for more info on this see the Hibernate Annotations Docs: package com.books; @Entity public class Book { private Long id; private String title; private String description; private Date date; @Id @GeneratedValue public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } } Once thats done we need to register the class with the Hibernate sessionFactory, to do so we add entries to the "%PROJECT_HOME%/hibernate/hibernate.cfg.xml" file as follows: <hibernate-configuration> <session-factory> <mapping package="com.books" /> <mapping class="com.books.Book" /> </session-factory> </hibernate-configuration> And thats it! When Grails loads it will register the necessary dynamic methods with the class! To see what else you can do with a Hibernate domain class see the section on Scaffolding |
![]() |
Document generated by Confluence on Mar 29, 2006 08:46 |